//
//  testProjectViewController.m
//  Myrna-Mindfulness
//
//  Created by Anders J.R. Petersen on 02/09/13.
//  Copyright (c) 2013 Anders J.R. Petersen. All rights reserved.
//

#import "GuideListViewController.h"
#import "GuidePlayerViewController.h"

@interface GuideListViewController(){}
@end



@implementation GuideListViewController
///
@synthesize selectedMeditation;
@synthesize selectedMeditationTitle;
@synthesize selectedMeditationDetails;
@synthesize selectedMeditationFile;
//

@synthesize productList;
@synthesize buttonList;

@synthesize productIDS;
@synthesize productTitles;
@synthesize productDetails;
@synthesize productFiles;

- (void)viewDidLoad
{
    [super viewDidLoad];

    //product 1
    NSString *p1ID      =   @"met1";
    NSString *p1Title   =   @"Opmærksomhedsøvelse";
    NSString *p1Details =   @"Dette er en guided opmærksomhedsøvelse på 10 minutter. Slap af og start øvelsen, ved at trykke på play knappen, når du er klar";
    NSString *p1File    =   @"met1";
    [[NSUserDefaults standardUserDefaults] setObject:p1File forKey:p1ID];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    //product 2
    NSString *p2ID      =   @"met2";
    NSString *p2Title   =   @"Opmærksomhedsøvelse";
    NSString *p2Details =   @"Dette er en guided opmærksomhedsøvelse på 15 minutter. Slap af og start øvelsen, ved at trykke på play knappen, når du er klar";
    NSString *p2File    =   @"";
    
    //product 3
    NSString *p3ID      =   @"met3";
    NSString *p3Title   =   @"Opmærksomhedsøvelse";
    NSString *p3Details =   @"Dette er en guided opmærksomhedsøvelse på 20 minutter. Slap af og start øvelsen, ved at trykke på play knappen, når du er klar";
    NSString *p3File    =   @"";
    
    //product 4
    NSString *p4ID      =   @"met4";
    NSString *p4Title   =   @"Ro i kroppen";
    NSString *p4Details =   @"Dette er en guided ro på 10 minutter. Slap af og start øvelsen, ved at trykke på play knappen, når du er klar";
    NSString *p4File    =   @"";
    
    //product 5
    NSString *p5ID      =   @"met5";
    NSString *p5Title   =   @"Stres af";
    NSString *p5Details =   @"Dette er en guided stress på 10 minutter. Slap af og start øvelsen, ved at trykke på play knappen, når du er klar";
    NSString *p5File    =   @"";
    
    //product 6
    NSString *p6ID      =   @"met6";
    NSString *p6Title   =   @"Sov godt";
    NSString *p6Details =   @"Dette er en guided sov på 15 minutter. Slap af og start øvelsen, ved at trykke på play knappen, når du er klar";
    NSString *p6File    =   @"";
    
    //product 7
        NSString *p7ID      =   @"met70";
    NSString *p7Title   =   @"Visualiseringsovelse";
    NSString *p7Details =   @"Dette er en guided visual på 20 minutter. Slap af og start øvelsen, ved at trykke på play knappen, når du er klar";
    NSString *p7File    =   @"";
    
    //product 8
    NSString *p8ID      =   @"met8";
    NSString *p8Title   =   @"Hjerteovelse";
    NSString *p8Details =   @"Dette er en guided hjerte på 20 minutter. Slap af og start øvelsen, ved at trykke på play knappen, når du er klar";
    NSString *p8File    =   @"";
    
    productIDS      = [NSArray arrayWithObjects: p1ID,      p2ID,       p3ID,       p4ID,       p5ID,       p6ID,       p7ID,       p8ID,       nil];
    buttonList      = [NSArray arrayWithObjects: b1,        b2,         b3,         b4,         b5,         b6,         b7,         b8,         nil];
    productTitles   = [NSArray arrayWithObjects: p1Title,   p2Title,    p3Title,    p4Title,    p5Title,    p6Title,    p7Title,    p8Title,    nil];
    productDetails  = [NSArray arrayWithObjects: p1Details, p2Details,  p3Details,  p4Details,  p5Details,  p6Details,  p7Details,  p8Details,  nil];
    productFiles    = [NSArray arrayWithObjects: p1File,    p2File,     p3File,     p4File,     p5File,     p6File,     p7File,     p8File,     nil];
    productList     = [[NSMutableArray alloc] init];
    
    //restoring completed transactions
    //[self restoringStuff];
    
    //unlock restored buttons
    [self initializeButtons];
    
    //start loading products
    if([SKPaymentQueue canMakePayments]){
        SKProductsRequest *productRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithArray:productIDS]];
        productRequest.delegate = self;
        [productRequest start];
    }else{
    }
}

- (void)restoringStuff
{
    //restoring payments
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"meditationsIsLoaded"]){
        
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
        //is loaded - yes
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"meditationsIsLoaded"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (IBAction)meditationSelected:(UIButton *)sender {
    int i = [buttonList indexOfObject:sender];
    selectedMeditation          =   [productIDS objectAtIndex:i];
    selectedMeditationTitle     =   [productTitles objectAtIndex:i];
    selectedMeditationDetails   =   [productDetails objectAtIndex:i];
    selectedMeditationFile      =   [[NSUserDefaults standardUserDefaults] objectForKey:selectedMeditation];  //TETSTING THE NEW DOWNLOADED URL //[productFiles objectAtIndex:i];
    [self startMeditationTransaction];
}

-(void)startMeditationTransaction{
    if([[NSUserDefaults standardUserDefaults] objectForKey:selectedMeditation]){
        [self performSegueWithIdentifier:@"play" sender:self];
    }else{
        [self makePayment:[self getProductByID:selectedMeditation]];
    }    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    GuidePlayerViewController *vc = [segue destinationViewController];
     if ([[segue identifier] isEqualToString:@"play"]) {
        [vc setHeaderText:selectedMeditationTitle];
        [vc setDetailsText:selectedMeditationDetails];
        [vc initializePlayer:selectedMeditationFile];
     }
}


-(void) makePayment:(SKProduct *) product{
    if(product){
        SKPayment *payment = [SKPayment paymentWithProduct:product];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Ingen forbindelse til butikken - prøv igen" delegate:self cancelButtonTitle:@"LUK" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *name;
    for(SKPaymentTransaction *transaction in transactions){
        switch (transaction.transactionState) {
                
            case SKPaymentTransactionStatePurchasing:
                break;
            case SKPaymentTransactionStatePurchased:
                //[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
                name = [[transaction payment] productIdentifier];
                //[self performSegueWithIdentifier:@"play" sender:self];
                
                //download stuff
                if (transaction.downloads) {
                    [[SKPaymentQueue defaultQueue] startDownloads:transaction.downloads];
                } else {
                    // unlock features
                    [defaults setObject:name forKey:name];
                    [defaults synchronize];
                    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                }
                
                break;
            case SKPaymentTransactionStateRestored:
                name = [[transaction payment] productIdentifier];
                [defaults setObject:name forKey:name];
                [defaults synchronize];
                
                break;
            case SKPaymentTransactionStateFailed:
                break;
            default:
                break;
        }
    }
    [self initializeButtons];
}

/////////////////////////// DOWNLOAD STUFF START ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

-(void)paymentQueue:(SKPaymentQueue *)queue updatedDownloads:(NSArray *)downloads
{
    for (SKDownload *download in downloads)
    {
        
        
        switch (download.downloadState) {
            case SKDownloadStateActive:
                    //is downloading
                    [self isDownloading:true];
        
                NSLog(@"Download progress = %f",
                      download.progress);
                NSLog(@"Download time = %f",
                      download.timeRemaining);
                break;
            case SKDownloadStateFinished:
                    //is downloading
                    [self isDownloading:false];
                
                [self processDownload:download]; // not written yet
                // now we're done
                [queue finishTransaction:download.transaction];
                
                break;
            default:
                break;
        }
    }
}

- (void)isDownloading: (bool) downloading
{
    if (downloading) {
        a.hidden = false;
        for(UIButton *b in buttonList){
            b.enabled = !downloading;
        }
    }else{
        a.hidden = true;
        for(UIButton *b in buttonList){
            b.enabled = !downloading;
        }
        
    }
    
    
}



- (void) processDownload:(SKDownload*)download;
{
    // convert url to string, suitable for NSFileManager
    NSString *path = [download.contentURL path];
    
    // files are in Contents directory
    path = [path stringByAppendingPathComponent:@"Contents"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *files = [fileManager contentsOfDirectoryAtPath:path error:&error];
    
    for (NSString *file in files) {
            NSString *fullPathSrc = [path stringByAppendingPathComponent:file];
        
            NSArray       *paths            = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString  *documentsDirectory   = [paths objectAtIndex:0];
            NSString *fullPathDst           = [documentsDirectory stringByAppendingPathComponent:file];
        
            // not allowed to overwrite files - remove destination file
            [fileManager removeItemAtPath:fullPathDst error:NULL];
        
    if ([fileManager moveItemAtPath:fullPathSrc toPath:fullPathDst error:&error] == NO) {
            NSLog(@"Error: unable to move item: %@", error);
       }
        
            NSUserDefaults *defaults        = [NSUserDefaults standardUserDefaults];
            NSString *name                  = [[download.transaction payment] productIdentifier];
            [defaults setObject:fullPathDst forKey:name];
            [defaults synchronize];

        
    
    }
    
    [self initializeButtons];

    
}



/////// DOWNLOAD ENDED ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


-(void)initializeButtons{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    for (int i = 0 ; i < [productIDS count]; i++ ) {
        if([defaults objectForKey:[productIDS objectAtIndex:i]]){
            [[buttonList objectAtIndex:i] setBackgroundImage:nil forState:UIControlStateNormal];
        }
    }
}

-(SKProduct *)getProductByID:(NSString *)productID{
    SKProduct *result = nil;
    for(SKProduct *product in productList) {
        if([[product productIdentifier] isEqualToString:productID]){
            result = product;
        }
    }
    return result;
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    for (SKProduct *validProduct in [response products]) {
        [productList addObject:validProduct];
    }
}

@end
